package com.ujiuye.userjson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ujiuye.userjson.entity.User;
import org.junit.Test;

import java.util.ArrayList;

public class userJson {
    @Test
    public void userToJson() throws JsonProcessingException {
        //创建user对象
        User u1 = new User(1001,"牛魔王","男",new int[]{99,100,101});
        //使用jaxkson工具类中的核心对象ObjectMapper转换java对象为json字符串
        ObjectMapper mapper = new ObjectMapper();
        //调用转换方法
        String s = mapper.writeValueAsString(u1);

        System.out.println(s);

    }

    @Test
    public void ArrayToJson() throws JsonProcessingException {
        Object arr[] = {1,true,"牛逼"};
        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(arr);
        System.out.println(s);

    }
    @Test
    public void userArrayToJson() throws JsonProcessingException {
        User u1 = new User(1001,"牛魔王","男",new int[]{99,100,101});
        User u2 = new User(1002,"铁扇妹妹","女",new int[]{99,102,101});

        ArrayList<User> list = new ArrayList<>();
        list.add(u1);
        list.add(u2);
        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(list);
        System.out.println(s);
    }
}
